package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.*;
import com.cskaoyan.service.OrderService;
import com.cskaoyan.utils.MyBatisUtil;
import com.cskaoyan.utils.TransactionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {

    @Override
    public PageData list(PageParameter pageParameter) {
        OrderListParameter parameter = (OrderListParameter) pageParameter;
        PageHelper.startPage(pageParameter.getPage(), parameter.getLimit());
        MarketOrderExample example = new MarketOrderExample();
        example.setOrderByClause(parameter.getSort() + " " + parameter.getOrder());
        MarketOrderExample.Criteria criteria = example.createCriteria().andDeletedEqualTo(false);

        Date start = parameter.getStart();
        Date end = parameter.getEnd();
        if (start != null && end != null) {
            criteria.andAddTimeBetween(start, end);
        }

        Short[] orderStatusArray = parameter.getOrderStatusArray();
        if (orderStatusArray != null && orderStatusArray.length > 0) {
            criteria.andOrderStatusIn(Arrays.asList(orderStatusArray));
        }

        Integer orderId = parameter.getOrderId();
        if (orderId != null && orderId != 0) {
            criteria.andIdEqualTo(orderId);
        }

        String orderSn = parameter.getOrderSn();
        if (orderSn != null && !orderSn.isEmpty()) {
            criteria.andOrderSnLike("%" + orderSn + "%");
        }

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketOrderMapper orderMapper = sqlSession.getMapper(MarketOrderMapper.class);
        List<MarketOrder> marketOrders = orderMapper.selectByExample(example);
        PageData pageData = PageData.list(marketOrders);
        sqlSession.close();
        return pageData;
    }

    @Override
    public OrderDetailData selectById(int id) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketOrderMapper orderMapper = sqlSession.getMapper(MarketOrderMapper.class);
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(id);
        MarketOrderGoodsMapper orderGoodsMapper = sqlSession.getMapper(MarketOrderGoodsMapper.class);
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria goodsCriteria = orderGoodsExample.createCriteria();
        goodsCriteria.andOrderIdEqualTo(id);
        List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        MarketUserMapper userMapper = sqlSession.getMapper(MarketUserMapper.class);
        MarketUser user = userMapper.selectByPrimaryKey(marketOrder.getUserId());
        sqlSession.close();
        OrderDetailData data = OrderDetailData.data(orderGoods, user, marketOrder);
        return data;
    }

    @Override
    public String refund(Integer orderId, BigDecimal refundMoney) {
        //跟据订单id修改订单状态为已退款203，退款金额，退款方式，退款时间，订单关闭时间，更新时间（market_order）做更新
        MarketOrderMapper orderMapper = TransactionUtil.getMapper(MarketOrderMapper.class);
        MarketOrder order = MarketOrder.builder()
                .orderStatus((short) 203)
                .refundAmount(refundMoney)
                .refundType("微信退款接口")
                .refundTime(new Date())
                .endTime(new Date())
                .updateTime(new Date())
                .id(orderId).build();
        int updateRows = orderMapper.updateByPrimaryKeySelective(order);
        System.out.println("updateRows = " + updateRows);
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        //跟据order_id得到goods表（market_order_goods表）做查询
        MarketOrderGoodsMapper orderGoodsMapper = TransactionUtil.getMapper(MarketOrderGoodsMapper.class);
        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        //通过goods表中的product_id和number增加货品数量，更新时间（market_goods_product表）做更新
        MarketGoodsProductMapper productMapper = TransactionUtil.getMapper(MarketGoodsProductMapper.class);
        for (MarketOrderGoods orderGoods : orderGoodsList) {
            MarketGoodsProduct oldProduct = productMapper.selectByPrimaryKey(orderGoods.getProductId());
            MarketGoodsProduct newProduct = MarketGoodsProduct.builder()
                    .number(oldProduct.getNumber() + orderGoods.getNumber())
                    .updateTime(new Date())
                    .id(oldProduct.getId()).build();
            productMapper.updateByPrimaryKeySelective(newProduct);
        }
        //跟据order_id修改优惠劵使用状态为0未使用，更新时间（market_coupon_user）做更新
        MarketCouponUserMapper couponUserMapper = TransactionUtil.getMapper(MarketCouponUserMapper.class);
        MarketCouponUser couponUser = MarketCouponUser.builder()
                .status((short) 0)
                .updateTime(new Date())
                .build();
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andOrderIdEqualTo(orderId);
        int updateRows2 = couponUserMapper.updateByExampleSelective(couponUser, couponUserExample);
        System.out.println("updateRows2 = " + updateRows2);
        return marketOrder.getOrderSn();
    }

    @Override
    public String ship(OrderShipParameter shipParameter) {
        //修改订单状态为301已发货，更新ship_sn和ship_channel，ship_time，update_time字段
        MarketOrderMapper orderMapper = TransactionUtil.getMapper(MarketOrderMapper.class);
        MarketOrder order = MarketOrder.builder()
                .orderStatus((short) 301)
                .id(shipParameter.getOrderId())
                .shipSn(shipParameter.getShipSn())
                .shipChannel(shipParameter.getShipChannel())
                .shipTime(new Date())
                .updateTime(new Date()).build();
        int updateRows = orderMapper.updateByPrimaryKeySelective(order);
        System.out.println("updateRows = " + updateRows);
        MarketOrder order1 = orderMapper.selectByPrimaryKey(shipParameter.getOrderId());
        return order1.getOrderSn();
    }

    @Override
    public String delete(Integer id) {
        MarketOrderMapper orderMapper = TransactionUtil.getMapper(MarketOrderMapper.class);
        MarketOrder order = MarketOrder.builder().id(id).deleted(true).build();
        orderMapper.updateByPrimaryKeySelective(order); //逻辑删除
//        orderMapper.deleteByPrimaryKey(id); //物理删除
        return orderMapper.selectByPrimaryKey(id).getOrderSn();
    }
}
